import { useLocalObservable } from 'mobx-react-lite'
import React, { FC, createContext, useContext } from 'react'
import * as CompleteStore from './modules'

// 生成store的统一方法 新增加一个store,在此创建一个实例即可
const createStores = () => ({ ...CompleteStore })

// Context的封装,创建 Provider，通过 React.Context来注入,包裹函数组件,将hookStores注入到函数组件中
const StoresContext = createContext(createStores())
// hooks组件使用的store hooks 使用笔记看这里 -> https://kgithub.com/olivewind/blog/issues/1
const useMobxStores = () => useContext(StoresContext)

type TStore = ReturnType<typeof createStores>
const StoreContext = createContext<TStore | null>(null)

// 创建 Provider，通过 React.Context 来注入
const MobxStoreProvider:FC<{ children: React.ReactNode }> = ({ children }) => {
  const hookStores = useLocalObservable(createStores) // 函数组件中hooks使用的store
  return (
    <StoreContext.Provider value={hookStores}>
      {children}
    </StoreContext.Provider>
  )
}

export { MobxStoreProvider, useMobxStores }
